/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import modelHeader from "./purchaseApplication.vue"
import modelHeader from "../purchase_application_not_mx/purchaseApplicationNotMx.vue"

// import modelHeader from "../purchase_not_mx/purchaseNotMx.vue"
import modelBody from "../../customerinfo/q_client/client.vue";
import gridHeader from "@/components/print/selectTemplet.vue"

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    mounted() {},
    async onInit() {
      this.queryFields = ['Supplier', 'CreateDate']

      this.textInline = false
      this.detailOptions.textInline = false
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == 'Attachment' || item.field == 'Image') {
            item.multiple = true;
            item.maxFile = 10;
          }
        })
      })
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]

      if (this.$route.path == "/q_purchase" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.PaymentState = null
        // this.searchFormFields.Supplier = null
        // this.searchFormFields.PaymentType = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Voucher_sub',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      if (this.$route.path == "/q_purchase_payment") {
        this.searchFormFields.AuditStatus = "1"
        this.searchFormFields.PaymentState = "0"
      }
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })

      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "未采购商品",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          // this.$refs.modelHeader.detailPurchaseApplicationOpen()
          this.$store.commit("setTabelText", true)
          this.$refs.modelHeader.open()
        }
      })

      if (this.$route.path != "/q_purchase") {
        this.setFiexdSearchForm(true);
        this.height = 550 - 150;
        this.buttons.forEach(item => {
          if (item.value != "Search") {
            item.hidden = true
          }
        })
        this.detailOptions.buttons = []
        //设置默认查询
      }

    },

    rowClick({
      row,
      column,
      event
    }) { //查询界面table点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row)
    },

    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_purchase" || this.rowAuditStatus != 0) {
        return
      } //|| !this.CreateUserBoole
      if (column.property == "Goods_price" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    //查询界面的删除
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path != "/q_purchase") {
        param.wheres = param.wheres.filter(item => item.name != "Purchase")
        this.$route.query = {}
      }
      if (this.$route.path == "/q_purchase" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Purchase", param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Purchase")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBeforeAsync(formData) {
      formData.mainData.PaymentState = "0"
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },

    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      //数据创建人和当前用户
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_purchase" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_purchase" || this.rowAuditStatus != 0) return false //|| !this.CreateUserBoole
        return true
      };
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Image") {
            // console.log("x", x)
            // x.uploadBefore = (files, params) => {
            //   files = new File([files], "123.png", {
            //     type: files.type
            //   })
            //   return true
            // }
          }
          if (x.field == 'Attachment') {
            try {
              //选择文件时
              // x.onChange = (files) => {
              //   console.log('选择文件事件', x)
              //   //此处不返回true，会中断代码执行
              //   for (let index = 0; index < files.length; index++) {
              //     if (files[index].name.includes(",")) {
              //       this.base.ElMessageFn("文件名中不允许包含逗号")
              //       return false;
              //     }
              //   }
              //   return true;
              // }
            } catch (error) {
              console.log(error);
            }
            x.fileTypes = ['pdf'];
          }
          if (x.field == "PaymentState") {
            x.hidden = true
          }
          if (x.field == "Voucher_sub" || x.field == "AuditStatus" || x.field == "Goods_num" || x.field == "Total_price" || x.field == "PaymentState" || x.field == "Goods_in_state") {
            x.disabled = true
          } else {
            x.disabled = false

          }
          // if (x.field == "Supplier") {
          //x.disabled = true
          // x.extra = {
          //   icon: "el-icon-zoom-in",
          //   text: "选择供应商",
          //   style: "color:#3a8ee6;font-size:13px;cursor:default",
          //   click: () => {
          //     this.$store.commit("setTabelText", true)
          //     this.$refs.modelBody.open()
          //   }
          // }
          // }
          if (this.$route.path != "/q_purchase" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
            if (x.field == "Supplier") {
              x.extra = null
            }
          }
        })
      })

    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let summaryPrc = 0
      let summaryNum = 0
      let num = 0
      await detailRowData.forEach(item => {
        summaryPrc += item.Goods_price * item.Goods_num
        summaryNum += +item.Goods_num
        if (item.Goods_sub && item.Goods_name && item.Goods_num && item.Goods_price) num++
      })
      // formData.mainData.Goods_num = summaryNum
      // formData.mainData.Total_price = summaryPrc
      console.log(num)
      if (detailRowData.length == num) {
        return true
      } else {
        this.base.ElMessageFn("请正确选择商品")
        return false
      }
    },
    async testAdd(formData) {

      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn('请选择采购机构')
        return false
      }
      let boole = formData.detailData.every(item => +item.Goods_price > 0 && +item.Goods_price)
      // let booleP2 = formData.detailData.every(item => +item.Goods_price == true || +item.Goods_price > 0)
      if (!boole) {
        this.base.ElMessageFn("采购单明细中单价请填写有效正数")
        return false;
      }
      // if (!booleP2) {
      //   this.base.ElMessageFn("采购单明细中单价请填写有效数字")
      //   return false;
      // }
      return true
    },

  }
};
export default extension;